package com.zhq.okhttp.subscribe;


import android.graphics.Bitmap;
import android.graphics.BitmapFactory;


import com.zhq.apputil.utils.LogUtil;
import com.zhq.constant.AppConstant;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ConnectException;
import java.net.SocketTimeoutException;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.ResponseBody;
import retrofit2.HttpException;

public class SubscriberImageThread implements Observer<ResponseBody> {
    private DownImageResponseListener listener;
    private Disposable disposable;
    private long totalBytesRead = 0;

    public SubscriberImageThread(DownImageResponseListener listener) {
        this.listener = listener;
    }

    @Override
    public void onError(Throwable e) {
        if (listener != null) {
            String msg = e.getLocalizedMessage();
            if (e instanceof SocketTimeoutException) {
                msg = "连接网络超时，请检查您的网络状态";
            } else if (e instanceof ConnectException) {
                msg = "网络中断，请检查您的网络状态";
            } else if (e instanceof HttpException) {
                msg = e.getMessage();
                HttpException httpException = (HttpException) e;
                int code = httpException.code();
                msg = httpException.getMessage();
                if (code == AppConstant.HttpResponse.NETWORK_CONNECT_TIME_OUT) {
                    msg = "网络不给力";
                }
            }
            LogUtil.e("onError：" + e.getLocalizedMessage());
            listener.requestFailure(msg);
        }
    }

    @Override
    public void onComplete() {
        removeDisposable();
    }


    @Override
    public void onSubscribe(Disposable d) {
        disposable = d;
    }

    @Override
    public void onNext(ResponseBody response) {
        if (listener != null) {
            try {
                LogUtil.e("image response.....");
                InputStream is = response.byteStream();
                BufferedInputStream bis = new BufferedInputStream(is);
                byte[] b = getBytes(is);
                Bitmap bitmap = BitmapFactory.decodeByteArray(b, 0, b.length);
                bis.close();
                listener.getBitmapImage(bitmap);
            } catch (Exception e) {//加载失败处理
                LogUtil.e("字节流：" + e.getLocalizedMessage());
                listener.requestFailure("加载失败");
            }
        } else {
            removeDisposable();
        }
    }

    /**
     * 将InputStream对象转换为Byte[]
     *
     * @param is
     * @return
     * @throws IOException
     */
    private byte[] getBytes(InputStream is) throws IOException {
        ByteArrayOutputStream byteOutStream = new ByteArrayOutputStream();
        byte[] b = new byte[1024];
        int len = 0;
        while ((len = is.read(b, 0, 1024)) != -1) {
            byteOutStream.write(b, 0, len);
            byteOutStream.flush();
        }
        byte[] bytes = byteOutStream.toByteArray();
        return bytes;
    }

    /**
     * 销毁disposable
     */
    private void removeDisposable() {
        if (disposable != null && !disposable.isDisposed()) {
            disposable.dispose();
            disposable = null;
        }
    }
}
